package com.laisheng.interview.controller;

import com.laisheng.interview.model.PageResult;
import com.laisheng.interview.mapper.AccountingInfoMapper;
import com.laisheng.interview.model.AccountingInfo;
import com.laisheng.interview.model.ResumeFile;
import com.laisheng.interview.service.impl.AccountingServiceImpl;
import com.laisheng.interview.service.NotificationService;
import com.laisheng.interview.service.ResumeFileService;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
/**
 * 面试信息控制器，处理面试信息提交、简历上传和数据查询等请求
 */
@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class AccountingController {
    @Autowired
    private AccountingInfoMapper accountingInfoMapper;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private ResumeFileService resumeFileService;
    
    @Autowired
    private com.laisheng.interview.mapper.DevelopmentExercisesMapper developmentExercisesMapper;
    @Autowired
    private com.laisheng.interview.mapper.ResumeFileMapper resumeFileMapper;

    /**
     * 保存面试者信息
     * @param accountingInfo 面试者信息对象
     * @param httpRequest HTTP请求对象
     * @return 包含操作结果和面试者ID的响应
     */
    @PostMapping(path = {"/api/user/submit","/api/accounting/save"})
    public Map<String, Object> saveAccountingInfo(@RequestBody AccountingInfo accountingInfo, HttpServletRequest httpRequest) {
        HttpSession session = httpRequest.getSession();
        Map<String, Object> response = new HashMap<>();
        try {
            accountingInfoMapper.insert(accountingInfo);
            // 添加：返回生成的主键ID
            session.setAttribute("accountingInfoId",accountingInfo.getId());
            response.put("accountingId", accountingInfo.getId());
            response.put("success", true);
            
            // 创建通知
            String title = "新的面试申请";
            String content = "收到来自 " + accountingInfo.getName() + " 的面试申请，申请职位：" + accountingInfo.getPosition();
            notificationService.createNotification(title, content, "accounting", accountingInfo.getId());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
    
    /**
     * 上传简历文件
     * @param file 简历文件（PDF格式）
     * @param accountingInfoId 面试者ID
     * @return 包含上传结果的响应
     */
    @PostMapping("/api/resume/upload")
    public Map<String, Object> uploadResume(@RequestParam("file") MultipartFile file, @RequestParam("accountingInfoId") Long accountingInfoId) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择文件");
                return response;
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                response.put("success", false);
                response.put("message", "只支持PDF格式文件");
                return response;
            }

            ResumeFile resumeFile = resumeFileService.uploadResume(file, accountingInfoId);
            response.put("success", true);
            response.put("data", resumeFile);
            response.put("message", "简历上传成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "简历上传失败: " + e.getMessage());
        }
        return response;
    }
    @Autowired
    private AccountingServiceImpl accountingServiceImpl;

    /**
     * 分页查询面试者信息
     * @param name 姓名模糊查询
     * @param date 日期筛选
     * @param page 页码
     * @param size 每页条数
     * @param sort 排序字段和方向
     * @return 分页查询结果
     */
    @GetMapping("/api/accounting/data")
    public PageResult getData(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String date,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "create_time,desc") String sort) {
        log.info("搜索参数 - name: {}, date: {}, page: {}, size: {}", name, date, page, size);
        return accountingServiceImpl.pageQuery(name, date, page, size, sort);
    }
    
    @PostMapping("/api/accounting/deleteByNameAndPhone")
    public Map<String, Object> deleteByNameAndPhone(@RequestBody Map<String, String> params) {
        Map<String, Object> resp = new HashMap<>();
        String name = params.get("name");
        String phone = params.get("phone");
        if (name == null || phone == null) {
            resp.put("success", false);
            resp.put("message", "姓名和手机号不能为空");
            return resp;
        }
        // 1. 查找用户
        AccountingInfo user = accountingInfoMapper.selectByNameAndPhone(name, phone);
        if (user == null) {
            resp.put("success", false);
            resp.put("message", "未找到匹配的数据");
            return resp;
        }
        Long userId = user.getId();
        // 2. 先删练习题
        try { developmentExercisesMapper.deleteByAccountingId(userId); } catch (Exception ignore) {}
        // 3. 再删简历
        try { resumeFileMapper.deleteByAccountingId(userId); } catch (Exception ignore) {}
        // 4. 最后删个人信息
        int count = accountingInfoMapper.deleteById(userId);
        if (count > 0) {
            resp.put("success", true);
            resp.put("message", "删除成功");
        } else {
            resp.put("success", false);
            resp.put("message", "删除失败");
        }
        return resp;
    }

}